//
//  ActionSearchViewController.m
//  EggSteward
//
//  Created by 王道林 on 16/9/9.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "ActionSearchViewController.h"
#import "DLWNetworkingParser.h"
#import "DLMacro.h"
#import "BaseTableView.h"
#import "SetTableViewCellO.h"
#import "BaseButton.h"
#import "BaseCollectionView.h"
#import "SearchFooterCollectionViewCell.h"
#import "CustomLayout.h"
#import "ActionSearchModel.h"
#import "ActionSearchDetailTableViewCell.h"
#import "Scene_tableViewCellNearT.h"
#import "ActionCycleModel.h"
#import "Home_NewsViewControllerWeb.h"
@interface ActionSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, CustomLayoutDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) BaseButton *buttonSearch;
@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) NSArray *arrTitle;
@property (nonatomic, strong) NSMutableArray *arrSearch;
@property (nonatomic, strong) BaseCollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *arrCity;
@property (nonatomic, strong) NSMutableArray *arrDate;
// 记录点击cell
@property (nonatomic, assign) BOOL recordOne;
@property (nonatomic, assign) BOOL recordTwo;
@property (nonatomic, assign) BOOL recordThree;
// 显示活动的Footer上的tableView
@property (nonatomic, strong) BaseTableView *tableViewActionDetail;
@property (nonatomic, strong) NSMutableArray *arrAction;
@end

@implementation ActionSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _recordOne = 0;
    _recordTwo = 0;
    _recordThree = 0;
    self.navigationItem.title = @"搜索";
    [self handleData];
    [self addGestureTapBackKey];
    [self createSubview];
    [self createTableFooterViewShouAction];
}

- (void)handleData
{
    _arrAction = [NSMutableArray array];
    _arrCity = [NSMutableArray array];
    _arrDate = [NSMutableArray array];
    // 城市的数据
    [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/active/index/getCity" par:nil success:^(id responseObject) {
        for (NSDictionary *dic in responseObject[@"data"]) {
            ActionSearchModel *model = [ActionSearchModel modelWithDic:dic];
            [_arrCity addObject:model];
        }
    } filed:^(NSError *error) {
        
    }];
    // 搜索时间的数据
    [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/active/index/getDate" par:nil success:^(id responseObject) {
        
        for (NSDictionary *dic in responseObject[@"data"]) {
            ActionSearchModel *model = [ActionSearchModel modelWithDic:dic];
            [_arrDate addObject:model];
        }
    } filed:^(NSError *error) {
        
    }];
    
    // row= 0 的标题
    self.arrTitle = @[@"搜索详细设置", @"选择所有搜索的地区", @"选择所要搜索的时间段"];
    // 那个历史搜索的数据
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString *pathdata = [[pathArray firstObject] stringByAppendingPathComponent:@"searchHistery"];
    _arrSearch = [NSMutableArray arrayWithContentsOfFile:pathdata];
    if (_arrSearch == nil) {
        _arrSearch = [NSMutableArray array];
    }
    
}

- (void)createSubview
{
    
    _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.delegate = self;
    [self createTableHeaderView];
    [self createTableFooterView];
    _tableView.dataSource = self;
    [self.view addSubview: _tableView];
    // 注册
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    [_tableView registerClass:[SetTableViewCellO class] forCellReuseIdentifier:@"reuseOne"];
    [_tableView registerClass:[ActionSearchDetailTableViewCell class] forCellReuseIdentifier:@"reuseDetail"];
    
}
#pragma mark - tableview 的协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _tableView)
    {
        if (_recordOne == 0)
        {
            return 1;
        } else
        {
            return 3;
        }
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableView)
    {
        if (_recordOne == 0) {
            return 1;
        }
        else
        {
            if (_recordTwo == 0 && _recordThree == 0)
            {
                return 1;
            } else if (_recordTwo == 1 && _recordThree == 0)
            {
                if (section == 1)
                {
                    return _arrCity.count +1;
                } else
                {
                    return 1;
                }
            } else if (_recordThree == 1 && _recordTwo ==0)
            {
                if (section == 2)
                {
                    return _arrDate.count + 1;
                } else
                {
                    return 1;
                }
            } else if (_recordTwo == 1 && _recordThree == 1)
            {
                if (section == 0) {
                    return 1;
                } else if (section == 1)
                {
                    return _arrCity.count + 1;
                }
                    return _arrDate.count + 1;
            } else
            {
                return 1;
            }
        }

    }
    return _arrAction.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        if (indexPath.section == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
            cell.textLabel.text = _arrTitle[indexPath.section];
            return cell;
        } else if (indexPath.section == 1)
        {
            if (indexPath.row == 0) {
                SetTableViewCellO *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseOne" forIndexPath:indexPath];
                cell.labelTitle.text = _arrTitle[indexPath.section];
                return cell;
            } else
            {
                ActionSearchDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseDetail" forIndexPath:indexPath];
                ActionSearchModel *model = _arrCity[indexPath.row - 1];
                cell.lable.text = model.province;
                cell.lable.textColor = [UIColor blackColor];
                cell.imgaeview.image = [UIImage imageNamed:@"xuanze"];
                return cell;
            }
        } else if (indexPath.section == 2)
        {
            if (indexPath.row == 0) {
                SetTableViewCellO *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseOne" forIndexPath:indexPath];
                cell.labelTitle.text = _arrTitle[indexPath.section];
                return cell;
            } else
            {
                ActionSearchDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseDetail" forIndexPath:indexPath];
                ActionSearchModel *model = _arrDate[indexPath.row - 1];
                cell.lable.text = model.value;
                cell.lable.textColor = [UIColor blackColor];
                cell.imgaeview.image = [UIImage imageNamed:@"xuanze"];
                return cell;
            }
            
        }

    }
    Scene_tableViewCellNearT *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseScene" forIndexPath:indexPath];
    ActionCycleModel *model = _arrAction[indexPath.row];
    cell.model = model;
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        return 50;
    }
    return 220;
}
// 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView)
    {
        if (indexPath.section == 0 && indexPath.row == 0)
        {
            _recordOne = !_recordOne;
            [_tableView reloadData];
        } else if (indexPath.section == 1 )
        {
            if (indexPath.row ==0)
            {
                if (_arrCity.count > 0)
                {
                    _recordTwo = !_recordTwo;
                    [_tableView reloadData];
                }
            } else
            {
                // 获取点击cell 后的活动数据
                [_arrAction removeAllObjects];
                [self.tableViewActionDetail reloadData];
                if (self.tableView.tableFooterView != _tableViewActionDetail) {
                    self.tableView.tableFooterView = _tableViewActionDetail;
                }
                ActionSearchModel *model = _arrCity[indexPath.row - 1];
                NSString *level = [NSString stringWithFormat:@"%ld", model.level];
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                NSString *ticket = [userDefault valueForKey:@"ticket"];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:ticket, @"ticket", @"38.889713", @"lat", @"121.550815", @"lon", @"0", @"type", model.province, @"province",level, @"level", nil];
                
                [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/active/Index/getList" par:dic success:^(id responseObject) {
                    for (NSDictionary *dic in responseObject[@"data"]) {
                        ActionCycleModel *model = [ActionCycleModel modelWithDic:dic];
                        [_arrAction addObject:model];
                        // 创建tableView的尾
                        [_tableViewActionDetail reloadData];
                    }
                    // 改变颜色
                    [_tableView reloadData];
                    ActionSearchDetailTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.lable.textColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
                    cell.imgaeview.image = [UIImage imageNamed:@"xuanze_s"];
                    
                } filed:^(NSError *error) {
                    
                }];
                
            }
        } else if (indexPath.section == 2)
        {
            if (indexPath.row == 0)
            {
                if (_arrDate.count > 0)
                {
                    _recordThree = !_recordThree;
                    [_tableView reloadData];
                }
            } else
            {
                // 获取点击cell 后的活动数据
                [_arrAction removeAllObjects];
                [self.tableViewActionDetail reloadData];
                if (self.tableView.tableFooterView != _tableViewActionDetail) {
                    self.tableView.tableFooterView = _tableViewActionDetail;
                }

                NSString *type = [NSString stringWithFormat:@"%ld", (indexPath.row - 1)];
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                NSString *ticket = [userDefault valueForKey:@"ticket"];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:ticket, @"ticket", @"38.889713", @"lat", @"121.550815", @"lon", type, @"type",@"1", @"level", nil];
                
                [DLWNetworkingParser POSTWithURL:@"http://api.danjiguanjia.com/active/Index/getList" par:dic success:^(id responseObject) {
                    for (NSDictionary *dic in responseObject[@"data"]) {
                        ActionCycleModel *model = [ActionCycleModel modelWithDic:dic];
                        [_arrAction addObject:model];
                        // 创建tableView的尾
                        [_tableViewActionDetail reloadData];
                    }
                } filed:^(NSError *error) {
                    
                }];
                // 改变颜色
                [_tableView reloadData];
                ActionSearchDetailTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                cell.lable.textColor = [UIColor colorWithRed:0.157 green:0.651 blue:0.278 alpha:1.000];
                cell.imgaeview.image = [UIImage imageNamed:@"xuanze_s"];
                
            }
        }

    } else
    {
        ActionCycleModel *model = _arrAction[indexPath.row];
        Home_NewsViewControllerWeb *webVC = [[Home_NewsViewControllerWeb alloc] init];
        webVC.name = @"actionNearOne";
        webVC.url = model.url;
        webVC.navigationTitle = @"活动详情";
        [self.navigationController pushViewController:webVC animated:YES];

    }
}



#pragma mark - 创建tableView的头,搜索
- (void)createTableHeaderView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    _tableView.tableHeaderView = view;
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.frame = CGRectMake(0, 0, VIEW_WIDTH - 50, 50);
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.placeholder = @"请填写您要搜索的内容";
    [view addSubview:_searchBar];
    
    _buttonSearch = [BaseButton buttonWithType:UIButtonTypeCustom];
    [_buttonSearch setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [_buttonSearch setBackgroundColor:[UIColor whiteColor]];
    _buttonSearch.frame = CGRectMake(VIEW_WIDTH - 50, 0, 50, 50);
    [_buttonSearch addTarget:self action:@selector(ButtonSearchAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:_buttonSearch];
}
#pragma mark -searchButton的查找按钮
- (void)ButtonSearchAction:(BaseButton *)button
{
    if (![_searchBar.text isEqualToString:@""]) {
        [_arrSearch insertObject:_searchBar.text atIndex:0];
        NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[arr firstObject] stringByAppendingPathComponent:@"searchHistery"];
        BOOL is = [_arrSearch writeToFile:path atomically:YES];
        if (is) {
            [_collectionView reloadData];
        }
    }
    
}


#pragma mark - 创建tableView的尾,, 自定义的layout
- (void)createTableFooterView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 500)];
    _tableView.tableFooterView = view;
    BaseLabel *label = [[BaseLabel alloc] initWithFrame:CGRectMake(10, 0, 100, 30)];
    label.text = @"最近搜索";
    label.textColor = [UIColor grayColor];
    [view addSubview:label];
    
    // 创建collectionView

    // 自定义layout
    CustomLayout *layout = [[CustomLayout alloc] init];
    layout.delegate = self;
    
    _collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(10, 40, VIEW_WIDTH - 20, 400) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [view addSubview:_collectionView];
    // 注册
    [_collectionView registerClass:[SearchFooterCollectionViewCell class] forCellWithReuseIdentifier:@"reuseLable"];
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _arrSearch.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchFooterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseLable" forIndexPath:indexPath];
    cell.label.text = _arrSearch[indexPath.row];
    return cell;
}

// 自定义layout的代理方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewCustomLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = _arrSearch[indexPath.row];
    CGRect rect =[string boundingRectWithSize:CGSizeMake(VIEW_WIDTH - 40, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
    CGFloat height = rect.size.height + 10;
    CGFloat width = rect.size.width + 10;
    CGSize size = CGSizeMake(width, height);
    return size;
}

// cell 的点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    _searchBar.text = _arrSearch[indexPath.row];
}


#pragma mark - 添加手势 回收键盘
- (void)addGestureTapBackKey
{
    UISwipeGestureRecognizer *SwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGetBackKey:)];
    SwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:SwipeGesture];
}

-(void)swipeGetBackKey:(UITapGestureRecognizer *)swipe
{
    [_searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 创建tableView的footerView.显示具体活动的
- (void)createTableFooterViewShouAction
{
    _tableViewActionDetail = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 500) style:UITableViewStyleGrouped];
    
    _tableViewActionDetail.delegate = self;
    _tableViewActionDetail.dataSource = self;
    _tableViewActionDetail.scrollEnabled = NO;
    // 注册tableViewCell
    [_tableViewActionDetail registerClass:[Scene_tableViewCellNearT class] forCellReuseIdentifier:@"reuseScene"];
    
}





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
